<template>
  <div class="home">
    <!-- 悬浮按钮和小弹层 -->
    <div class='floatbox'>
      <button 
        class='aibut'
        @click="toggleSpeechRecognition" 
        :class="{ 'listening': isListening }"
        @mouseenter="showSmallPopup = true"
        @mouseleave="handleButtonMouseLeave"
      >
      AI
      </button>
      
      <!-- 小弹层 -->
      <div 
        class="small-popup"
        v-show="showSmallPopup"
        @mouseenter="showSmallPopup = true"
        @mouseleave="showSmallPopup = false"
      >
        <span class="ai">
          <div @click="showLargePopup = true">思考中...</div>
          <button @click="pauseInteraction">暂停</button>
        </span>
      </div>
    </div>

    <!-- 大弹层 - 展示AI对话记录 -->
    <div 
      class="large-popup"
      v-show="showLargePopup"
      @click="handleLargePopupClick"
    >
      <div class="popup-content-container">
        <div class="popup-header">
          <h3>与AI的对话</h3>
          <button @click="showLargePopup = false" class="close-btn">×</button>
        </div>
        <!-- 对话记录区域 -->
        <div class="popup-conversation">
          <!-- 空状态提示 -->
          <div class="empty-state" v-if="conversation.length === 0">
            <img src="https://picsum.photos/100/100?random=empty" alt="空对话" class="empty-img">
            <p>还没有对话记录哦~</p>
            <p>开始与小韵聊天吧！</p>
          </div>
          
          <!-- 对话列表 -->
          <div class="message-list" v-else>
            <div 
              class="message-item" 
              :class="{'user-message': msg.role === 'user', 'ai-message': msg.role === 'assistant'}"
              v-for="(msg, index) in conversation" 
              :key="index"
            >
              <div class="message-avatar">
                <span v-if="msg.role === 'user'">我</span>
                <span v-if="msg.role === 'assistant'">韵</span>
              </div>
              <div class="message-content">
                {{ msg.content }}
              </div>
            </div>
          </div>
        </div>
        
        <!-- 对话输入输入区域 -->
        <div class="popup-input-area">
          <textarea 
            v-model="userInput" 
            placeholder="输入消息..." 
            @keyup.enter="sendMessageInPopup"
            class="popup-input"
          ></textarea>
          <button @click="pauseInteraction" class="send-btn">暂停</button>
          <button @click="sendMessageInPopup" class="send-btn">发送</button>
        </div>
      </div>
    </div>
    
    <div class="header">
      <div class="greeting">hello~!</div>
      <div class="user-card">
        <div class="user-profile">
          <div class="user-name">{{ userName }}</div>
          <img :src="userAvatar" class="user-avatar" alt="用户头像" @error="handleAvatarError">
        </div>
      </div>
    </div>
    
    <div class="yesterday-sports-data">
      <div class="section-title">昨日运动数据</div>
      <div class="data-container">
        <div class="icon-container">
          <img src="https://cdn-icons-png.flaticon.com/512/2990/2990103.png" alt="户外跑步图标" class="sport-icon">
          <div class="sport-name">户外跑步</div>
        </div>
        <div class="heart-rate-container" @click="startHeartRateSimulation">
          <div class="heart-rate-circle" :class="{'blinking': isBlinking}">
            <div class="heart-rate-value" :class="{'danger-text': heartRateStatus === '危险'}">{{ currentHeartRate }}次/分钟</div>
            <div class="heart-rate-label">{{ heartRateStatus }}</div>
          </div>
        </div>
      </div>
      <div class='text'>
        <div class="data-item">
          <div class="item-label">运动距离</div>
          <div class="item-value">5.66km</div>
        </div>
        <div class="data-item">
          <div class="item-label">运动时间</div>
          <div class="item-value">00:56:05</div>
        </div>
        <div class="data-item">
          <div class="item-label">运动消耗</div>
          <div class="item-value">362千卡</div>
        </div>
      </div>
    </div>
    
    <div class="this-week-sports-stats">
      <div class="section-title">本周运动量数据统计</div>
      <div class="stats-image-container">
        <img src="/data.png" alt="本周运动量数据统计" class="stats-image" @error="handleStatsImageError">
      </div>
    </div>
    
    <!-- 今日健身音乐区域 -->
    <div class="today-fitness-music" @click="showMusicDialog = true">
      <div class="section-title">今日健身音乐</div>
      <div class="music-card">
        <img 
          :src="currentMusic.cover" 
          alt="music cover" 
          class="music-cover" 
          @error="handleMusicCoverError"
        >
        <div class="music-info">
          <div class="music-name">{{ currentMusic.name }}</div>
          <div class="music-artist">{{ currentMusic.artist }}</div>
        </div>
        <div class="play-pause-icon" @click.stop="togglePlayerPlay">
          <i class="fa" :class="isPlaying ? 'fa-pause' : 'fa-play'"></i>
        </div>
      </div>
      <div class="progress-container">
        <div class="progress-time">
          <span>{{ formatTime(currentTime) }}</span>
          <span>{{ formatTime(duration) }}</span>
        </div>
        <input 
          type="range" 
          min="0" 
          :max="duration" 
          :value="currentTime" 
          class="progress-bar"
          @input="updatePlayerProgress"
          @click.stop
        >
      </div>
      <audio 
        ref="audioPlayer" 
        :src="currentMusic.src" 
        @timeupdate="handleTimeUpdate" 
        @loadedmetadata="handleLoadedMetadata"
        @ended="handleEnded"
        hidden
      ></audio>
    </div>
    
    <div class="bottom-nav">
      <div class="nav-item active">
        <i class="fa fa-home"></i>
        <span>首页</span>
      </div>
      <div class="nav-item">
        <i class="fa fa-users"></i>
        <span>社区</span>
      </div>
      <div class="nav-item">
        <i class="fa fa-video-camera"></i>
        <span>视频</span>
      </div>
      <div class="nav-item">
        <i class="fa fa-user"></i>
        <span>我的</span>
      </div>
    </div>

    <!-- 心率过高警告弹窗 -->
    <div v-if="showEmergencyDialog" class="emergency-dialog-overlay">
      <div class="emergency-dialog">
        <h3>⚠️ 心率过高警告</h3>
        <p>您的心率已达到危险水平({{ currentHeartRate }}次/分钟)</p>
        <p>请立即停止运动并休息</p>
        <button @click="closeEmergencyDialog" class="close-dialog-button">我知道了</button>
      </div>
    </div>

    <!-- 音乐选择弹窗 -->
    <div v-if="showMusicDialog" class="music-dialog-overlay">
      <div class="music-dialog">
        <h3>选择健身音乐</h3>
        <div class="music-list">
          <div v-if="!isSearchMode" class="music-item add-music-item" @click="switchToSearchMode">
            <div class="add-music-placeholder">
              <i class="fa fa-plus"></i> 添加新音乐
            </div>
          </div>
          
          <div v-if="isSearchMode" class="search-container">
            <input 
              type="text" 
              v-model="searchKeyword" 
              class="music-search-input"
              placeholder="搜索音乐..."
              @keyup.enter="confirmSearch"
              ref="searchInput"
              @input="handleSearchInput"
            >
            
            <div class="search-suggestions" v-if="searchSuggestions.length > 0">
              <div 
                class="suggestion-item" 
                v-for="(suggestion, index) in searchSuggestions" 
                :key="index"
                @click="selectSuggestion(suggestion)"
              >
                <img :src="suggestion.cover" alt="cover" class="suggestion-cover" @error="handleSuggestionCoverError">
                <div class="suggestion-info">
                  <div class="suggestion-name">{{ suggestion.name }}</div>
                  <div class="suggestion-artist">{{ suggestion.artist }}</div>
                </div>
              </div>
            </div>
          </div>
          
          <div 
            class="music-item" 
            v-for="(music, index) in musicList" 
            :key="music.id"
            @click="selectMusic(index)"
            :class="{ 'selected': currentMusic.id === music.id }"
          >
            <img :src="music.cover" alt="cover" class="music-item-cover" @error="handleMusicItemCoverError($event, index)">
            <div class="music-item-info">
              <div class="music-item-name">{{ music.name }}</div>
              <div class="music-item-artist">{{ music.artist }}</div>
            </div>
            <i class="fa fa-check" v-if="currentMusic.id === music.id"></i>
            
            <button 
              @click.stop="deleteMusic(index)" 
              class="music-delete-button"
              :disabled="musicList.length <= 1"
              title="删除音乐"
            >
              ×
            </button>
          </div>
        </div>
        <button @click="showMusicDialog = false" class="close-music-dialog">关闭</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from 'vue';
import axios from 'axios';

// 新增弹层状态
const showSmallPopup = ref(false);
const showLargePopup = ref(false);
const isButtonClicking = ref(false); // 标记按钮是否正在被点击
const hasTriggeredHighIntensity = ref(false); // 防止重复触发高强度提示
const hasTriggeredDanger = ref(false); // 防止重复触发危险提示

// 处理按钮鼠标离开事件 - 增加延迟时间，确保用户有足够时间移动到小弹层
const handleButtonMouseLeave = () => {
  // 如果正在点击按钮，则不立即隐藏
  if (isButtonClicking.value) return;
  
  // 延长延迟时间到300ms，给用户更多时间移动鼠标
  setTimeout(() => {
    // 检查鼠标是否已经进入小弹层区域
    const smallPopup = document.querySelector('.small-popup');
    const isMouseOverPopup = smallPopup?.matches(':hover');
    
    if (!showLargePopup.value && !isMouseOverPopup) {
      showSmallPopup.value = false;
    }
  }, 300);
};

// 处理大弹层点击事件
const handleLargePopupClick = (e: MouseEvent) => {
  // 如果点击的是弹层背景，则关闭
  if ((e.target as HTMLElement).classList.contains('large-popup')) {
    showLargePopup.value = false;
  }
};

// 在弹窗中发送消息
const sendMessageInPopup = () => {
  sendMessage();
  // 发送后保持弹窗打开，自动滚动到底部
  nextTick(() => {
    const msgList = document.querySelector('.popup-conversation .message-list') as HTMLElement;
    if (msgList) {
      msgList.scrollTop = msgList.scrollHeight;
    }
  });
};

// 对话消息列表
const conversation = ref<{ role: 'user' | 'assistant'; content: string }[]>([]);
// 用户输入内容
const userInput = ref('');
// 语音合成实例
const synth = ref<SpeechSynthesis | null>(window.speechSynthesis);
// 当前语音合成的语音实例
const currentUtterance = ref<SpeechSynthesisUtterance | null>(null);
// 语音识别实例
const recognition = ref<any>(null);
// 是否正在录音
const isListening = ref(false);

// 初始化语音识别
const initSpeechRecognition = () => {
  if ('webkitSpeechRecognition' in window) {
    recognition.value = new (window as any).webkitSpeechRecognition();
  } else if ('SpeechRecognition' in window) {
    recognition.value = new (window as any).SpeechRecognition();
  } else {
    alert('您的浏览器不支持语音识别功能');
    return;
  }
  recognition.value.lang = 'zh-CN';
  recognition.value.interimResults = false;
  recognition.value.onresult = (event: any) => {
    const transcript = event.results[0][0].transcript;
    userInput.value = transcript;
    sendMessage();
  };
  recognition.value.onend = () => {
    isListening.value = false;
  };
  recognition.value.onerror = (event: any) => {
    console.error('语音识别错误:', event.error);
    isListening.value = false;
  };
};

// 切换语音识别状态 - 新增点击状态管理
const toggleSpeechRecognition = () => {
  // 标记按钮正在被点击
  isButtonClicking.value = true;
  
  if (!recognition.value) {
    initSpeechRecognition();
  }

  if (isListening.value) {
    recognition.value?.stop();
  } else {
    recognition.value?.start();
    isListening.value = true;
    // 确保点击语音按钮时小弹层仍然显示
    showSmallPopup.value = true;
  }
  
  // 短暂延迟后重置点击状态
  setTimeout(() => {
    isButtonClicking.value = false;
  }, 300);
};

// 暂停交互函数
const pauseInteraction = () => {
  // 停止语音识别
  if (recognition.value && isListening.value) {
    recognition.value.stop();
    isListening.value = false;
  }
  // 停止语音合成
  if (synth.value && synth.value.speaking) {
    synth.value.cancel();
    currentUtterance.value = null;
  }
  const pauseMessage = { role: 'assistant', content: '已暂停交互，您可以随时继续使用' };
conversation.value.push(pauseMessage as { role: 'user' | 'assistant'; content: string });

  // 朗读 AI 回复
  speakText(pauseMessage.content);

  // 滚动到最新消息
  scrollToConversationBottom();
};

// 发送消息函数
const sendMessage = async () => {
  if (!userInput.value.trim()) return;

  // 添加用户消息到对话列表
  const userMessage = { role: 'user', content: userInput.value.trim() };
conversation.value.push(userMessage as { role: 'user' | 'assistant'; content: string });
  userInput.value = '';

  try {
    // 调用 AI 接口获取回复
    const response = await axios.post(
      'https://api.deepseek.com/chat/completions',
      {
        model: 'deepseek-chat',
        messages: conversation.value
      },
      {
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer sk-329970a063324a14abdd8f8cfc299188`
        }
      }
    );

    // 添加 AI 回复到对话列表
    const aiMessage = {
      role: 'assistant',
      content: response.data.choices[0].message.content
    };
conversation.value.push(aiMessage as { role: 'user' | 'assistant'; content: string });

    // 朗读 AI 回复
    speakText(aiMessage.content);
  } catch (error) {
    console.error('获取 AI 回复失败:', error);
    // 添加错误提示到对话列表
    const errorMessage = {
      role: 'assistant',
      content: '抱歉，获取回复时出错，请稍后再试。'
    };
conversation.value.push(errorMessage as { role: 'user' | 'assistant'; content: string });
    // 朗读错误提示
    speakText(errorMessage.content);
  }
  // 滚动到最新消息
  scrollToConversationBottom();
};

// 滚动到对话底部
const scrollToConversationBottom = () => {
  nextTick(() => {
    const msgList = document.querySelector('.popup-conversation .message-list') as HTMLElement;
    if (msgList) {
      msgList.scrollTop = msgList.scrollHeight;
    }
  });
};

// 语音合成函数
const speakText = (text: string) => {
  if (synth.value && synth.value.speaking) {
    synth.value.cancel();
  }

  const utterance = new SpeechSynthesisUtterance(text);
  utterance.lang = 'zh-CN';
  utterance.volume = 1; // 音量，范围 0 - 1
  utterance.rate = 1; // 语速，范围 0.1 - 10
  utterance.pitch = 1; // 音调，范围 0 - 2

  currentUtterance.value = utterance;
  synth.value?.speak(utterance);
};

// 心率状态变化处理函数
const handleHeartRateStatusChange = (newStatus: string) => {
  // 当心率状态为"运动强度较大"时触发语音提示
  if (newStatus === '运动强度较大' && !hasTriggeredHighIntensity.value) {
    hasTriggeredHighIntensity.value = true;
    speakText('当前心率较大建议休息');
    
    // 添加到对话记录
    conversation.value.push({
      role: 'assistant',
      content: '当前心率较大建议休息'
    });
    
    // 30秒后重置，允许再次触发
    setTimeout(() => {
      hasTriggeredHighIntensity.value = false;
    }, 30000);
  }
  
  // 当心率状态为"危险"时触发语音提示
  if (newStatus === '危险' && !hasTriggeredDanger.value) {
    hasTriggeredDanger.value = true;
    speakText('检测到危险，长按开机键说出紧急呼叫人姓名');
    
    // 添加到对话记录
    conversation.value.push({
      role: 'assistant',
      content: '检测到危险，长按开机键说出紧急呼叫人姓名'
    });
    
    // 1分钟后重置，允许再次触发
    setTimeout(() => {
      hasTriggeredDanger.value = false;
    }, 60000);
  }
};

onMounted(() => {
  // 检查浏览器是否支持语音合成
  if (!('speechSynthesis' in window)) {
    alert('您的浏览器不支持语音合成功能');
  }
  // 初始化语音识别
  initSpeechRecognition();

  // 监听对话变化，自动滚动到底部
  watch(conversation, () => {
    scrollToConversationBottom();
  });

  // 监听鼠标是否悬停在小弹层上，用于更精确的状态管理
  document.addEventListener('mousemove', () => {
    const smallPopup = document.querySelector('.small-popup');
    if (smallPopup && showSmallPopup.value) {
      const isHovering = smallPopup.matches(':hover');
      if (isHovering) {
        showSmallPopup.value = true;
      }
    }
  });

  // 监听心率状态变化
  watch(heartRateStatus, (newVal) => {
    handleHeartRateStatusChange(newVal);
  });
});

// 用户信息
const userName = ref('王紫冰');
const userAvatar = ref('');
const defaultAvatar = 'https://picsum.photos/100';

// 心率相关状态
const currentHeartRate = ref(72);
let simulationInterval: number | null = null;
const isBlinking = ref(false);
const showEmergencyDialog = ref(false);
const heartRateStatus = ref('正常');
const isSimulating = ref(false);

// 语音交互核心状态
const speechSynthesis = window.speechSynthesis;
const voiceResult = ref('');
const barHeights = ref<string[]>(Array(10).fill('10px'));
let audioContext: AudioContext | null = null;
let analyser: AnalyserNode | null = null;
let microphone: MediaStreamAudioSourceNode | null = null;
let animationId: number | null = null;
let sessionId = ref(''); // 会话ID，用于多轮对话上下文
const isProcessing = ref(false); // 防止重复提交

// AI输入框状态
const isAiInputVisible = ref(false);
const showConversationModal = ref(false);

// 音乐播放相关
const musicList = ref([
  {
    id: 1,
    name: '《江南style》-健身版',
    artist: 'PSY',
    cover: 'https://picsum.photos/100?random=101',
    src: 'https://samplelib.com/lib/preview/mp3/sample-6s.mp3'
  },
  {
    id: 2,
    name: '《Eye of the Tiger》',
    artist: 'Survivor',
    cover: 'https://picsum.photos/100?random=102',
    src: 'https://samplelib.com/lib/preview/mp3/sample-9s.mp3'
  },
  {
    id: 3,
    name: '《Can\'t Stop the Feeling!》',
    artist: 'Justin Timberlake',
    cover: 'https://picsum.photos/100?random=103',
    src: 'https://samplelib.com/lib/preview/mp3/sample-12s.mp3'
  },
  {
    id: 4,
    name: '《Stronger》',
    artist: 'Kanye West',
    cover: 'https://picsum.photos/100?random=104',
    src: 'https://samplelib.com/lib/preview/mp3/sample-15s.mp3'
  }
]);

const currentMusic = ref(musicList.value[0]);
const audioPlayer = ref<HTMLAudioElement | null>(null);
const isPlaying = ref(false);
const currentTime = ref(0);
const duration = ref(0);
const showMusicDialog = ref(false);

// 搜索相关状态
const isSearchMode = ref(false);
const searchKeyword = ref('');
const searchSuggestions = ref([]);
const nextMusicId = ref(5);

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await axios.get('http://localhost:3000/getlogin');
    if (response.data.data && response.data.data.length > 0) {
      const userData = response.data.data[0];
      userName.value = userData.name || '用户';
      userAvatar.value = userData.img || defaultAvatar;
      localStorage.setItem('currentUser', JSON.stringify(userData));
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    userName.value = '用户';
    userAvatar.value = defaultAvatar;
  }
};

// 错误处理
const handleAvatarError = (e: Event) => {
  const target = e.target as HTMLImageElement;
  target.src = defaultAvatar;
};

const handleStatsImageError = (e: Event) => {
  const target = e.target as HTMLImageElement;
  target.src = 'https://picsum.photos/300/140?random=stats';
};

const handleMusicCoverError = (e: Event) => {
  const target = e.target as HTMLImageElement;
  target.src = 'https://picsum.photos/60/60?random=default';
};

const handleMusicItemCoverError = (e: Event, index: number) => {
  const target = e.target as HTMLImageElement;
  target.src = `https://picsum.photos/50/50?random=item${index}`;
};

const handleSuggestionCoverError = (e: Event) => {
  const target = e.target as HTMLImageElement;
  target.src = 'https://picsum.photos/50/50?random=suggestdefault';
};

// 心率状态更新
const updateHeartRateStatus = () => {
  const hr = currentHeartRate.value;
  let newStatus = '正常';
  
  if (hr >= 60 && hr <= 90) {
    newStatus = '正常';
    isBlinking.value = false;
  } else if (hr >= 91 && hr <= 110) {
    newStatus = '运动强度较低';
    isBlinking.value = false;
  } else if (hr >= 111 && hr <= 150) {
    newStatus = '运动最佳期';
    isBlinking.value = false;
  } else if (hr >= 151 && hr <= 170) {
    newStatus = '运动强度较大';
    isBlinking.value = false;
  } else if (hr >= 171) {
    newStatus = '危险';
    isBlinking.value = true;
    showEmergencyDialog.value = true;
  }
  
  // 只有当状态变化时才更新
  if (heartRateStatus.value !== newStatus) {
    heartRateStatus.value = newStatus;
  }
};

const closeEmergencyDialog = () => {
  showEmergencyDialog.value = false;
};

// 音乐控制
const togglePlayerPlay = () => {
  if (!audioPlayer.value) return;
  if (isPlaying.value) {
    audioPlayer.value.pause();
  } else {
    audioPlayer.value.play().catch(err => {
      console.error('播放失败:', err);
      alert('播放失败，请检查音频地址是否有效');
    });
  }
  isPlaying.value = !isPlaying.value;
};

const handleTimeUpdate = () => {
  if (audioPlayer.value) {
    currentTime.value = audioPlayer.value.currentTime;
  }
};

const handleLoadedMetadata = () => {
  if (audioPlayer.value) {
    duration.value = audioPlayer.value.duration;
  }
};

const handleEnded = () => {
  isPlaying.value = false;
  currentTime.value = 0;
};

const updatePlayerProgress = (e: Event) => {
  if (!audioPlayer.value) return;
  const target = e.target as HTMLInputElement;
  const newTime = Number(target.value);
  audioPlayer.value.currentTime = newTime;
  currentTime.value = newTime;
};

const formatTime = (time: number) => {
  const minutes = Math.floor(time / 60);
  const seconds = Math.floor(time % 60);
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
};

const selectMusic = (index: number) => {
  if (audioPlayer.value) {
    audioPlayer.value.pause();
  }
  
  currentMusic.value = musicList.value[index];
  isPlaying.value = false;
  currentTime.value = 0;
  
  nextTick(() => {
    audioPlayer.value?.load();
  });
};

// 心率模拟
const startHeartRateSimulation = () => {
  if (isSimulating.value) return;
  
  stopHeartRateSimulation();
  
  isSimulating.value = true;
  currentHeartRate.value = 60;
  showEmergencyDialog.value = false;
  updateHeartRateStatus();
  
  simulationInterval = window.setInterval(() => {
    if (currentHeartRate.value < 190) {
      currentHeartRate.value += 1;
      updateHeartRateStatus();
    } else {
      stopHeartRateSimulation();
    }
  }, 300);
};

const stopHeartRateSimulation = () => {
  if (simulationInterval) {
    clearInterval(simulationInterval);
    simulationInterval = null;
  }
  isSimulating.value = false;
};

// 音乐搜索功能
const switchToSearchMode = () => {
  isSearchMode.value = true;
  searchKeyword.value = '';
  searchSuggestions.value = [];
  
  nextTick(() => {
    const input = document.querySelector('.music-search-input') as HTMLInputElement;
    input?.focus();
  });
};

const handleSearchInput = () => {
  if (!searchKeyword.value.trim()) {
    searchSuggestions.value = [];
    return;
  }
  
  const keyword = searchKeyword.value.toLowerCase();
  
  const mockMusicDatabase = [
    { name: 'Shape of You', artist: 'Ed Sheeran', cover: 'https://picsum.photos/100?random=1' },
    { name: 'Uptown Funk', artist: 'Mark Ronson ft. Bruno Mars', cover: 'https://picsum.photos/100?random=2' },
    { name: 'Can\'t Stop the Feeling', artist: 'Justin Timberlake', cover: 'https://picsum.photos/100?random=3' },
    { name: 'Happy', artist: 'Pharrell Williams', cover: 'https://picsum.photos/100?random=4' },
    { name: 'Shut Up and Dance', artist: 'WALK THE MOON', cover: 'https://picsum.photos/100?random=5' },
    { name: 'Levitating', artist: 'Dua Lipa', cover: 'https://picsum.photos/100?random=6' },
    { name: 'Blinding Lights', artist: 'The Weeknd', cover: 'https://picsum.photos/100?random=7' },
    { name: 'Dynamite', artist: 'BTS', cover: 'https://picsum.photos/100?random=8' },
    { name: 'Sugar', artist: 'Maroon 5', cover: 'https://picsum.photos/100?random=9' },
    { name: 'Bad Guy', artist: 'Billie Eilish', cover: 'https://picsum.photos/100?random=10' },
  ];
  
  const filtered = mockMusicDatabase.filter(item => 
    item.name.toLowerCase().includes(keyword) || 
    item.artist.toLowerCase().includes(keyword)
  );
  
  const suggestionsWithSrc = filtered.map(item => ({
    ...item,
    src: `https://samplelib.com/lib/preview/mp3/sample-${(Math.floor(Math.random() * 5) + 6)}s.mp3`
  }));
  
  searchSuggestions.value = suggestionsWithSrc.slice(0, 5);
};

const selectSuggestion = (suggestion: any) => {
  musicList.value.push({
    id: nextMusicId.value++,
    name: suggestion.name,
    artist: suggestion.artist,
    cover: suggestion.cover,
    src: suggestion.src
  });
  
  localStorage.setItem('fitnessMusic', JSON.stringify(musicList.value));
  
  isSearchMode.value = false;
  searchKeyword.value = '';
  searchSuggestions.value = [];
};

const confirmSearch = () => {
  if (searchSuggestions.value.length > 0) {
    selectSuggestion(searchSuggestions.value[0]);
  } else if (searchKeyword.value.trim()) {
    const newMusic = {
      id: nextMusicId.value++,
      name: searchKeyword.value,
      artist: '未知艺术家',
      cover: `https://picsum.photos/100?random=${Date.now()}`,
      src: `https://samplelib.com/lib/preview/mp3/sample-15s.mp3`
    };
    
    musicList.value.push(newMusic);
    localStorage.setItem('fitnessMusic', JSON.stringify(musicList.value));
    
    isSearchMode.value = false;
    searchKeyword.value = '';
  }
};

const deleteMusic = (index: number) => {
  if (musicList.value.length <= 1) {
    alert('至少需要保留一首音乐');
    return;
  }
  
  const isCurrentPlaying = currentMusic.value.id === musicList.value[index].id;
  if (isCurrentPlaying && audioPlayer.value) {
    audioPlayer.value.pause();
    currentMusic.value = musicList.value[0];
    nextTick(() => audioPlayer.value?.load());
  }
  
  musicList.value.splice(index, 1);
  localStorage.setItem('fitnessMusic', JSON.stringify(musicList.value));
};

// 初始化
onMounted(async () => {
  try {
    // 生成会话ID
    sessionId.value = Date.now().toString();
    
    // 加载用户信息
    fetchUserInfo();
    
    // 检查浏览器支持
    if (!('speechSynthesis' in window)) {
      alert('您的浏览器不支持语音合成功能');
    }
    
    // 尝试加载本地保存的音乐列表
    const savedMusic = localStorage.getItem('fitnessMusic');
    if (savedMusic) {
      try {
        const parsedMusic = JSON.parse(savedMusic);
        if (Array.isArray(parsedMusic) && parsedMusic.length > 0) {
          musicList.value = parsedMusic;
          currentMusic.value = parsedMusic[0];
          nextMusicId.value = Math.max(...parsedMusic.map(m => m.id)) + 1;
        }
      } catch (e) {
        console.error('解析音乐列表失败', e);
      }
    }
    
  } catch (error) {
    console.error('初始化失败:', error);
  }
});

</script>

<style scoped>
/* 新增弹层样式 */
.floatbox {
  position: fixed;
  bottom: 45vh;
  right: 30px;
  z-index: 100;
}

.small-popup {
  position: absolute;
  left:-150px;
  top:5px;
  background: white;
  border-radius: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0,0,0,0.2);
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 101;
  /* 增加小弹层的点击区域范围 */
  padding: 10px 20px;
  min-width: 120px;
  text-align: center;
}

.small-popup:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.3);
}

.large-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
}

.popup-content-container {
  width: 100%;
  max-width: 600px;
  background: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 5px 20px rgba(0,0,0,0.3);
  display: flex;
  flex-direction: column;
  height: 80vh;
  max-height: 600px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #eee;
}

.popup-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
  color: #666;
}
.ai{
  display:flex;
}
.close-btn:hover {
  background-color: #e0e0e0;
}

/* 对话记录区域样式 */
.popup-conversation {
  flex: 1;
  overflow-y: auto;
  padding: 10px 20px;
  background-color: #fafafa;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  text-align: center;
  padding: 10px;
}

.empty-img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-bottom: 10px;
  opacity: 0.6;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  height: 100%;
}

.message-item {
  width: 80%;
  display: flex;
  animation: fadeIn 0.3s ease;
}

/* 调整对齐方式，保持不同角色消息在两侧但宽度一致 */
.user-message {
  margin-left: auto;
  justify-content: flex-end;
}

.ai-message {
  margin-right: auto;
  justify-content: flex-start;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  font-size: 14px;
  font-weight: 500;
}

/* 调整头像位置 */
.user-message .message-avatar {
  margin-left: 8px;
  background-color: #54EA8C;
  color: white;
  order: 2; /* 调整顺序，将头像放在消息右侧 */
}

.ai-message .message-avatar {
  margin-right: 8px;
  background-color: #e6f7ff;
  color: #1890ff;
  order: 1; /* 保持头像在消息左侧 */
}

.message-content {
  padding: 10px 15px;
  border-radius: 18px;
  line-height: 1.5;
  font-size: 14px;
  flex: 1;
  word-wrap: break-word;
  max-width: calc(100% - 44px);
}

.user-message .message-content {
  background-color: #54EA8C;
  color: white;
  border-top-right-radius: 4px;
  order: 1; /* 消息内容在左侧 */
}

.ai-message .message-content {
  background-color: #f0f0f0;
  color: #333;
  border-top-left-radius: 4px;
  order: 2; /* 消息内容在右侧 */
}

/* 弹窗输入区域 */
.popup-input-area {
  display: flex;
  padding: 10px 20px;
  border-top: 1px solid #eee;
  background-color: #f9f9f9;
  gap: 10px;
}

.popup-input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 20px;
  resize: none;
  font-size: 14px;
  height: 42px;
  outline: none;
}

.popup-input:focus {
  border-color: #54EA8C;
}

.send-btn {
  width: 42px;
  height: 42px;
  border-radius: 50%;
  background-color: #54EA8C;
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.send-btn:hover {
  background-color: #3ad073;
}

/* 主页面样式 */
.home {
  padding: 10px;
  background-color: #f8f9fa;
  position: relative;
  min-height: 100vh;
  padding-bottom: 70px;
}

.aibut{
  width:50px;
  height:50px;
  border:0px;
  background-color: pink;
  border-radius:50px;
  cursor: pointer;
  transition: transform 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 16px;
  color: white;
}

.aibut:hover {
  transform: scale(1.05);
}

.audio-visualizer {
  position: absolute;
  bottom: 5px;
  left: 0;
  right: 0;
  height: 20px;
  display: flex;
  justify-content: center;
  gap: 2px;
}

.audio-bar {
  width: 3px;
  background-color: white;
  border-radius: 1px;
  transition: height 0.1s ease;
}

.ai-avatar::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: conic-gradient(
    rgba(84, 234, 140, 0.8),
    rgba(76, 175, 80, 0.6),
    rgba(102, 187, 106, 0.8),
    rgba(84, 234, 140, 0.8)
  );
  opacity: 0;
  transition: opacity 0.3s ease;
  animation: rotate 3s linear infinite;
  z-index: -1;
}

.ai-avatar.speaking {
  transform: scale(1.05);
}

.ai-avatar.speaking::before {
  opacity: 1;
  padding: 2px;
  border-radius: 50%;
  animation: rotate 3s linear infinite;
}

@keyframes rotate {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.ai-input-container {
  position: fixed;
  left: -300px;
  top: 50%;
  transform: translateY(-50%);
  width: 280px;
  z-index: 90;
  transition: left 0.3s ease;
}

.ai-input-container.visible {
  left: 20px;
}

.ai-input-box {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.ai-input-box:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

.input-prompt {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
}

.ai-placeholder {
  color: #999;
  font-size: 14px;
}

.last-message {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.conversation-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 300;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  background-color: white;
  border-radius: 12px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  position: relative;
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 10px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-modal {
  background: none;
  border: none;
  font-size: 20px;
  color: #666;
  cursor: pointer;
}

.modal-body {
  flex: 1;
  padding: 10px 20px;
  overflow-y: auto;
}

.modal-footer {
  padding: 10px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
}

.clear-history {
  background-color: #f5f5f5;
  color: #666;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.clear-history i {
  margin-right: 6px;
}

.chat-input {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.chat-input textarea {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  resize: none;
  height: 50px;
}

.chat-input button {
  padding: 0 15px;
  background-color: #54EA8C;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.chat-input button:last-child {
  background-color: #f0f0f0;
  color: #666;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.greeting {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.user-card {
  display: flex;
  align-items: center;
  background: linear-gradient(135deg, #eef7fa, #d4f0f9);
  padding: 10px 16px;
  border-radius: 24px;
  box-shadow: 0 4px 12px rgba(0, 150, 255, 0.15);
}
.user-profile {
  display: flex;
  align-items: center;
}
.user-name {
  font-size: 18px;
  font-weight: 600;
  margin-right: 12px;
  color: #333;
}
.user-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e0f2fe;
  box-shadow: 0 2px 8px rgba(0, 150, 255, 0.2);
}

.yesterday-sports-data {
  background-color: white;
  padding: 10px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
}
.section-title {
  font-size: 18px;
  margin-bottom: 10px;
  color: #333;
  font-weight: 600;
}
.data-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.icon-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.sport-icon {
  width: 50px;
  height: 50px;
}
.sport-name {
  margin-top: 5px;
  color: #555;
  font-size: 14px;
}
.text {
  display: flex;
  justify-content: space-between;
}
.data-item {
  flex: 1;
  text-align: center;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin: 0 5px;
}
.item-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}
.item-value {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}
.heart-rate-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.heart-rate-circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 5px solid #f5f5f5;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f9fafc;
}
.heart-rate-value {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}
.danger-text {
  color: #ff0000 !important;
}
.heart-rate-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}
.blinking {
  animation: blink 1s infinite;
  border-color: #ff0000;
}
@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.this-week-sports-stats {
  background-color: white;
  padding: 10px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
}
.stats-image-container {
  width: 100%;
  height: 140px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}
.stats-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.today-fitness-music {
  background-color: white;
  padding: 10px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
  cursor: pointer;
}
.music-card {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 10px;
  margin-bottom: 10px;
}
.music-cover {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 15px;
}
.music-info {
  flex: 1;
}
.music-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}
.music-artist {
  font-size: 14px;
  color: #666;
}
.play-pause-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #54EA8C;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-left: 15px;
  font-size: 18px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.play-pause-icon:hover {
  background-color: #3ad073;
}
.progress-container {
  margin-top: 10px;
}
.progress-time {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}
.progress-bar {
  width: 100%;
  height: 4px;
  -webkit-appearance: none;
  appearance: none;
  background: #e0e0e0;
  outline: none;
  border-radius: 2px;
  cursor: pointer;
}
.progress-bar::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background: #54EA8C;
  cursor: pointer;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  background-color: white;
  padding: 10px 0;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}
.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #666;
  font-size: 12px;
}
.nav-item i {
  font-size: 20px;
  margin-bottom: 4px;
}
.nav-item.active {
  color: #54EA8C;
}

.emergency-dialog-overlay, .music-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 200;
}

.emergency-dialog, .music-dialog {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  text-align: center;
}

.emergency-dialog {
  animation: shake 0.5s;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
  20%, 40%, 60%, 80% { transform: translateX(5px); }
}

.emergency-dialog h3 {
  color: #ff0000;
  margin-bottom: 15px;
  font-size: 20px;
}

.emergency-dialog p {
  color: #333;
  margin-bottom: 15px;
  line-height: 1.6;
}

.close-dialog-button {
  width: 100%;
  padding: 12px;
  background-color: #54EA8C;
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 16px;
  margin-top: 10px;
}

.close-dialog-button:hover {
  background-color: #3ad073;
}

.music-dialog h3 {
  color: #333;
  margin-bottom: 10px;
  text-align: center;
  font-size: 18px;
}

.music-list {
  margin-bottom: 10px;
}

.music-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 8px;
  margin-bottom: 8px;
  background-color: #f8f9fa;
  cursor: pointer;
  transition: background-color 0.2s;
  position: relative;
  padding-right: 60px;
}

.music-item:hover {
  background-color: #f0f0f0;
}

.music-item.selected {
  background-color: #e8f5e9;
  border: 1px solid #c8e6c9;
}

.music-item-cover {
  width: 50px;
  height: 50px;
  border-radius: 6px;
  object-fit: cover;
  margin-right: 12px;
}

.music-item-info {
  flex: 1;
}

.music-item-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 2px;
}

.music-item-artist {
  font-size: 13px;
  color: #666;
}

.music-item .fa-check {
  color: #54EA8C;
  font-size: 18px;
  position: absolute;
  right: 35px;
}

.add-music-item {
  justify-content: center;
  border: 1px dashed #ccc;
  background-color: #f9f9f9;
}

.add-music-placeholder {
  display: flex;
  align-items: center;
  color: #666;
}

.add-music-placeholder i {
  margin-right: 8px;
}

.search-container {
  margin-bottom: 8px;
}

.music-search-input {
  width: 100%;
  padding: 10px;
  border-radius: 8px;
  border: 1px solid #ddd;
  font-size: 16px;
  margin-bottom: 10px;
}

.search-suggestions {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  max-height: 200px;
  overflow-y: auto;
}

.suggestion-item {
  display: flex;
  align-items: center;
  padding: 8px 10px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.suggestion-item:hover {
  background-color: #f5f5f5;
}

.suggestion-cover {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  margin-right: 10px;
}

.suggestion-name {
  font-size: 14px;
  color: #333;
}

.suggestion-artist {
  font-size: 12px;
  color: #666;
}

.music-delete-button {
  position: absolute;
  right: 10px;
  background-color: transparent;
  border: none;
  color: #ff0000;
  font-size: 18px;
  cursor: pointer;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s;
}

.music-delete-button:hover {
  background-color: #ffeeee;
}

.music-delete-button:disabled {
  color: #ccc;
  cursor: not-allowed;
}

.close-music-dialog {
  width: 100%;
  padding: 10px;
  background-color: #54EA8C;
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.close-music-dialog:hover {
  background-color: #3ad073;
}
</style>